package cn.cas.mango.util.RequestUtil;

import cn.cas.mango.dto.HotListDetail;
import cn.cas.mango.dto.param.HotListDetailParam;
import cn.cas.mango.dto.param.SearchHotParam;
import cn.cas.mango.service.ConfigService;
import cn.cas.mango.service.PartitionIndexService;
import cn.cas.mango.util.TimeUtil;
import cn.cas.mango.util.string.StringUtils;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch.core.CountRequest;
import co.elastic.clients.elasticsearch.core.CountResponse;
import co.elastic.clients.elasticsearch.core.SearchRequest;

import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SearchHotRequest {
  @Autowired
  ElasticsearchClient elasticsearchClient;
  @Autowired
  PartitionIndexService partitionIndexService;
  @Autowired
  ConfigService configService;
  private  BoolQuery.Builder wrapBool(SearchHotParam param) {
    String startDate = param.getStartDate();
    String endDate = param.getEndDate();
    BoolQuery.Builder bool = new BoolQuery.Builder();
    if (param.getSearchMode() == 2) {
      bool.must(
          b->b.match(m->m.field("title").query(param.getTitle()).minimumShouldMatch(String.format("%d%%", (int)(param.getSimWeight() * 100))))
      );
    } else {
      bool.must(
          b->b.matchPhrase(m->m.field("title").query(param.getTitle()))
      );
    }
    bool.filter(f -> f.range(r -> r.field("insert_time").gte(JsonData.of(startDate))
        .lte(JsonData.of(endDate))));
    return bool;
  }



  public SearchRequest.Builder buildRequest(SearchHotParam param) {
    SearchRequest.Builder builder = new SearchRequest.Builder();
    BoolQuery.Builder bool = wrapBool(param);
    int from = param.getPageNo() - 1;
    int size = param.getPageSize();
    String startDate = StringUtils.transTime2Date(param.getStartDate());
    String endDate = StringUtils.transTime2Date(param.getEndDate());
    String index = configService.getIndex();
    index = partitionIndexService.partitionIndex(index, startDate, endDate);
    builder.index(index).query(q->q.bool(bool.build())).from(from).size(size);
    if (!param.getIfAgg()) {
      builder.source(s->s.filter(f->f.excludes("vector")));
    }

    return builder;
  }


}
